import api from "@/api";
import { Toast } from "vant";
import { isMobile, isArray } from "@/utils/validate";

const state = {
  adInfo: {},
  order_sn: "",
  mobile_firest_template: {},
  mobile_second_template: {},
  pc_firest_template: {},
  customer: {},
};
const getters = {
  tpl(state) {
    return isMobile ? state.mobile_firest_template : state.pc_firest_template;
  },

  tplData(_, getters) {
    const { tpl_data } = getters.tpl;
    try {
      return JSON.parse(tpl_data);
    } catch (e) {
      return {};
    }
  },
  behaviorList(_, getters) {
    const { behavior } = getters.tpl;
    return (behavior || []).map((v) => ({
      ...v,
      post_type: v.post_type || "js_web",
    }));
  },
  config(_, getters) {
    return getters.tplData.config || {};
  },
  views(_, getters) {
    const { views } = getters.tplData;
    return (views || []).map((v) => {
      if (v.type.includes("group-buy")) {
        v.share_type = "group-buy";
        v.options.fixed_height += 0.2;
        v.options.discount_money = v.options.discount_money || 0;
      }
      if (v.type.includes("shop")) {
        v.share_type = "shop";
      }
      return v;
    });
  },
};
const actions = {
  // 落地页信息 - 获取
  async adView({ commit }, params) {
    // params.ad_url = window.location.href;
    const res = await api.getAdView(params).catch((e) => {
      Toast({
        message: e,
        position: "top",
      });
      throw e;
    });

    commit("SET_AD_INFO", res);
    return res;
  },
  // 客服信息 - 获取
  async adCustomer({ commit }, params) {
    const res = await api.getAdCustomer(params);
    if (!isArray(res)) {
      commit("SET_CUS", res);
    }
    return res;
  },
  async adSubmit(_, { uniEnv, ...params }) {
    return api[uniEnv.miniprogram ? "mpAdSubmit" : "adSubmit"](params);
  },
};
const mutations = {
  SET_AD_INFO(state, data) {
    state.adInfo = data;
    state.order_sn = data.order_sn;
    state.mobile_firest_template = data.mobile_firest_template;
    state.mobile_second_template = data.mobile_second_template;
    state.pc_firest_template = data.pc_firest_template;
  },
  SET_CUS(state, data) {
    // console.log(data);
    state.customer = data;
  },
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
